package com.sdruixinggroup.mondayb2b.ui;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.adapter.HotAdapter;
import com.sdruixinggroup.mondayb2b.adapter.QuickAdapter;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.HotSearch;
import com.sdruixinggroup.mondayb2b.models.SearchHistory;
import com.sdruixinggroup.mondayb2b.models.SearchResult;
import com.sdruixinggroup.mondayb2b.utils.SharedPreferenceUtil;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.utils.SharedPreferenceUtil.SP_CUSTOMER_HISTORY_NAME;

/**
 * Created by tangjie on 2017/11/11.
 */

public class SearchActivity extends BaseActivity {
    @BindView(R.id.et_search)
    EditText etSearch;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.hot_recyclerview)
    RecyclerView hotRecyclerview;
    private SearchAdapter searchAdapter;
    private TextView cancle;
    private List<SearchHistory> data;
    private LinearLayout clearAll;
    private InputMethodManager imm;
    private String keyWord = "";
    private HotAdapter adapter;
    private List<HotSearch.KeywordsBean> keywordsBeen ;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);

        keywordsBeen = new ArrayList<>();
        adapter =new  HotAdapter();
        adapter.setData(keywordsBeen);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),3);
        hotRecyclerview.setLayoutManager(gridLayoutManager);
        hotRecyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<HotSearch.KeywordsBean>(){
            @Override
            public void OnItemClick(HotSearch.KeywordsBean data, int postion) {

            }
        });
        searchAdapter = new SearchAdapter();
        data = new ArrayList<>();
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        searchAdapter.setData(data);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);

        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.clear_search_customer_history_view, null, false);
        clearAll = (LinearLayout) view.findViewById(R.id.ll_clear_all);
        searchAdapter.setFooterView(view);
        clearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences(SP_CUSTOMER_HISTORY_NAME, MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.clear();
                editor.commit();
                data.clear();
                searchAdapter.notifyDataSetChanged();
            }
        });

        recyclerView.setAdapter(searchAdapter);

        cancle = (TextView) findViewById(R.id.cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    String key = v.getText().toString().trim();
                    if (!TextUtils.isEmpty(key)) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                        getWindow().setSoftInputMode(
                                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

                        data.add(new SearchHistory(key));
                        searchAdapter.reflashData(data);
                        SharedPreferenceUtil.saveList(getApplicationContext(), data);

                        keyWord = key;
                        searchGoods(UserInfoUtil.AREA_CODE,keyWord);
                    } else {
                        showToast("请输入搜索参数");

                    }

                    return true;
                }

                return false;
            }
        });
        queryData();
    }

    private void queryData(){
            String url = API.SEARCH_HOT_KEYWORDS + UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<HotSearch> typeToken = new TypeToken<HotSearch>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<HotSearch>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(HotSearch response, int id) {
                    data.clear();

                if (null != response) {
                    if (response.getErr_code() == 0) {
                        List<HotSearch.KeywordsBean> dataBeen = response.getKeywords();
                        if (null != dataBeen && !dataBeen.isEmpty()) {
                            keywordsBeen.addAll(dataBeen);
                        }
                        adapter.reflashData(keywordsBeen);
                    } else {
                        showToast(response.getErr_msg());
                    }
                }

            }
        });
    }


    private void searchGoods(int area_id,String keywords){
        String url = API.GOODS+"area_id=" +area_id +"&keywords="+keywords+"&access_token="+UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<SearchResult> typeToken = new TypeToken<SearchResult>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<SearchResult>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(SearchResult response, int id) {

                if (null != response) {
                    if (response.getErr_code() == 0) {
                    } else {
                        showToast(response.getErr_msg());
                    }
                }

            }
        });
    }
}
